package demo;

import java.io.File;
import java.io.IOException;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

public class Searcher {
	public static void search(String indexDir, String q) throws IOException, ParseException {
		// 3) Open index
		Directory dir = FSDirectory.open(new File(indexDir));
		IndexReader reader = IndexReader.open(dir);
		IndexSearcher searcher = new IndexSearcher(reader);
		
		// 4) Parser query
		QueryParser parser = new QueryParser(Version.LUCENE_36, 
				                             "contents", 
				                             new StandardAnalyzer(Version.LUCENE_36));
		Query query = parser.parse(q);
		
		// 5) Search index
		long start = System.currentTimeMillis();
		TopDocs hits = searcher.search(query, 10);
		long end = System.currentTimeMillis();
		
		// 6) Write search stat
		System.err.println("Found " + hits.totalHits + " document(s) (in "
				+ (end - start) + " milliseconds) that matched query '" + q
				+ "':");
		
		// 7) Retrieve matching docs
		for (ScoreDoc scoreDoc : hits.scoreDocs) {
			Document doc = searcher.doc(scoreDoc.doc);
			System.out.printf(String.format("%s (%.02f)\n", doc.get("fullpath"), scoreDoc.score));
		}
		
		// 8) Close IndexSearcher
		searcher.close();
	}
	
	public static void main(String[] args) throws IllegalArgumentException,
			IOException, ParseException {
		if (args.length != 2) {
			throw new IllegalArgumentException("Usage: java "
					+ Searcher.class.getName() + " <index dir> <query>");
		}
		String indexDir = args[0];	// 1) Parser provided index directory
		String q = args[1];			// 2) Parser provided query string
		search(indexDir, q);
	}
}
